/*jslint white: true, browser: true, undef: true, nomen: true, eqeqeq: true, plusplus: false, bitwise: true, regexp: true, strict: true, newcap: true, immed: true, maxerr: 14 */
/*global window: false, ActiveXObject: false*/

/*
The onreadystatechange property is a function that receives the feedback. It is important to note that the feedback
function must be assigned before each send, because upon request completion the onreadystatechange property is reset.
This is evident in the Mozilla and Firefox source.
*/

/* enable strict mode */
"use strict";

// global variables
var progress,			// progress element reference
  request,			// request object
  intervalID = false;	// interval ID
  intervalID2 = false;	// interval ID
  intervalID4 = false;	// interval ID

// define reference to the progress bar and create XMLHttp request object
window.onload = function () {
  step_1 = document.getElementById('step_1');
  step_2 = document.getElementById('step_2');
  step_3 = document.getElementById('step_3');
  request = initXMLHttpClient();
  request2 = initXMLHttpClient();
  request3 = initXMLHttpClient();
  request4 = initXMLHttpClient();
}

// create XMLHttp request object in a cross-browser manner
function initXMLHttpClient() {
  var XMLHTTP_IDS,
    xmlhttp,
    success = false,
    i;
  // Mozilla/Chrome/Safari/IE7/IE8 (normal browsers)
  try {
    xmlhttp = new XMLHttpRequest(); 
  }
  // IE(?!)
  catch (e1) {
    XMLHTTP_IDS = [ 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
            'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP' ];
    for (i = 0; i < XMLHTTP_IDS.length && !success; i++) {
      try {
        success = true;
        xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
      }
      catch (e2) {}
    }
    if (!success) {
      throw new Error('Unable to create XMLHttpRequest!');
    }
  }
  return xmlhttp;
}

// send request to the server
function send_request() {

  var filename = document.getElementById('filename').value;
  var id = document.getElementById('id').value;
  
  request.open('GET', 'index.php?module=VoteThailandPoll&type=ajax&func=migrate&step=1&file='+filename+"&id="+id, true);	// open asynchronus request
  request.onreadystatechange = request_handler;		// set request handler	
  request.send(null);									// send request
}

// request handler (defined in send_request)
function request_handler() {
  var level,data;
  if (request.readyState === 4) { // if state = 4 (operation is completed)
    if (request.status === 200) { // and the HTTP status is OK
      if(request.responseText == "finished"){
        step2_start();
        polling_start3();
      }
    }else { // if request status isn't OK
      progress.style.width = '100%';
      progress.innerHTML = 'Error: [' + request.status + '] ' + request.statusText;
    }        
  }
}


// send request to the server
function send_request2() {
  var id = document.getElementById('id').value;
  request2.open('GET', 'index.php?module=VoteThailandPoll&type=ajax&func=csvprocess&id='+id, true);	// open asynchronus request
  request2.onreadystatechange = request_handler2;		// set request handler	
  request2.send(null);									// send request
}

// request handler (defined in send_request)
function request_handler2() {
  var level,data;
  result2 = document.getElementById('result2');
  result1 = document.getElementById('result1');
  if (request2.readyState === 4) { // if state = 4 (operation is completed)
    if (request2.status === 200) { // and the HTTP status is OK
      // get progress from the XML node and set progress bar width and innerHTML
      level = request2.responseXML.getElementsByTagName('PROGRESS')[0].firstChild;
      allcsv = request2.responseXML.getElementsByTagName('ALLCSV')[0].firstChild;
      csv = request2.responseXML.getElementsByTagName('CSV')[0].firstChild;

      if(level.nodeValue > 0 && level.nodeValue < 100 ){
        step_1.style.color = 'white';
        step_1.style.backgroundColor = '#339900';
        step_1.style.width = step_1.innerHTML = level.nodeValue + '%';
        result1.innerHTML = allcsv.nodeValue;
        result2.innerHTML = csv.nodeValue;
      }else if(allcsv.nodeValue == csv.nodeValue ){
        step_1.style.color = 'white';
        step_1.style.backgroundColor = '#339900';
        step_1.style.width = step_1.innerHTML = level.nodeValue + '%';
        result1.innerHTML = allcsv.nodeValue;
        result2.innerHTML = csv.nodeValue;
        window.clearInterval(intervalID2);
        intervalID2 = false;
      }
    }
    else { // if request status isn't OK
      step_1.style.width = progress.innerHTML = 100 + '%';
      step_1.style.width = '100%';
      step_1.innerHTML = 'Error: [' + request2.status + '] ' + request2.statusText;
    }        
  }
}

function send_request3(){
  var id = document.getElementById('id').value;
  request3.open('GET', 'index.php?module=VoteThailandPoll&type=ajax&func=migrate&step=2&id='+id, true);	// open asynchronus request
  request3.onreadystatechange = request_handler3;		// set request handler	
  request3.send(null);									// send request
}

// request handler (defined in send_request)
function request_handler3() {
  var level,data;
  if (request3.readyState === 4) { // if state = 4 (operation is completed)
    if (request3.status === 200) { // and the HTTP status is OK

    }else { // if request status isn't OK
      progress.style.width = '100%';
      progress.innerHTML = 'Error: [' + request.status + '] ' + request.statusText;
    }        
  }
}


// send request to the server
function send_request4() {
  var id = document.getElementById('id').value;
  request4.open('GET', 'index.php?module=VoteThailandPoll&type=ajax&func=dataprocess&id='+id, true);	// open asynchronus request
  request4.onreadystatechange = request_handler4;		// set request handler	
  request4.send(null);									// send request
}

// request handler (defined in send_request)
function request_handler4() {
  var level,data;
  result3 = document.getElementById('result3');
  result4 = document.getElementById('result4');
  result5 = document.getElementById('result5');
  result6 = document.getElementById('result6');
  if (request4.readyState === 4) { // if state = 4 (operation is completed)
    if (request4.status === 200) { // and the HTTP status is OK
      // get progress from the XML node and set progress bar width and innerHTML
      level = request4.responseXML.getElementsByTagName('PROGRESS')[0].firstChild;
      alldata = request4.responseXML.getElementsByTagName('ALLDATA')[0].firstChild;
      data = request4.responseXML.getElementsByTagName('DATA')[0].firstChild;

      if(level.nodeValue > 0 && level.nodeValue < 100 ){
        step_2.style.color = 'white';
        step_2.style.backgroundColor = '#339900';
        step_2.style.width = step_2.innerHTML = level.nodeValue + '%';
        result3.innerHTML = alldata.nodeValue;
        result4.innerHTML = data.nodeValue;
      }else if(alldata.nodeValue == data.nodeValue ){
        step_2.style.color = 'white';
        step_2.style.backgroundColor = '#339900';
        step_2.style.width = step_2.innerHTML = level.nodeValue + '%';
        result3.innerHTML = alldata.nodeValue;
        result4.innerHTML = data.nodeValue;
        window.clearInterval(intervalID4);
        intervalID4 = false;

        result5.innerHTML = alldata.nodeValue;
        result6.innerHTML = data.nodeValue;
        step_3.style.color = 'white';
        step_3.style.backgroundColor = '#339900';
        step_3.style.width = step_3.innerHTML = level.nodeValue + '%';
      }
    }
    else { // if request status isn't OK
      step_2.style.width = progress.innerHTML = 100 + '%';
      step_2.style.width = '100%';
      step_2.innerHTML = 'Error: [' + request2.status + '] ' + request2.statusText;
    }        
  }
}


// button actions (start / stop)
function polling_start() {
  var btn = document.getElementById('migrate_button'); 
  btn.disabled = 'true';
  btn.style.backgroundColor = '#CCCCCC';

  send_request();
}

// button actions (start / stop)
function step2_start() {
  send_request3();
}

// button actions (start / stop)
function polling_start2() {
  if (!intervalID2) {
    intervalID2 = window.setInterval('send_request2()', 1000);
  }
}


// button actions (start / stop)
function polling_start3() {
  if (!intervalID4) {
    intervalID4 = window.setInterval('send_request4()', 1000);
  }
}

function polling_stop() {
  window.clearInterval(intervalID);
  intervalID = false;
}

function polling_stop2() {
  window.clearInterval(intervalID2);
  intervalID2 = false;
}

